import { useRef, useCallback } from 'react';

// 时间戳数据结构
interface TimestampData {
  text: string;
  start: number;
  end: number;
  phoneme?: string;
}

// Viseme时间序列
interface VisemeTimeline {
  viseme: string;
  startTime: number;
  endTime: number;
  duration: number;
  text: string;
  phoneme?: string;
}

// 插值类型枚举
const InterpolationType = {
  LINEAR: 'linear',
  EASE_IN_OUT: 'easeInOut',
  EASE_IN: 'easeIn',
  EASE_OUT: 'easeOut',
  CUBIC_BEZIER: 'cubicBezier'
} as const;

// 插值配置
interface InterpolationConfig {
  type: string;
  duration: number;
  easing?: number[];
  delay?: number;
}

// 拼音到Viseme的映射表
const PINYIN_TO_VISEME_MAP: Record<string, string> = {
  // V0 - 静音（标点符号、空格）
  ' ': 'V0', '，': 'V0', '。': 'V0', '！': 'V0', '？': 'V0', '、': 'V0', '；': 'V0', '：': 'V0',
  '（': 'V0', '）': 'V0', '【': 'V0', '】': 'V0',
  
  // V1 - 双唇音 (b, p, m)
  'b': 'V1', 'ba': 'V1', 'bai': 'V1', 'ban': 'V1', 'bang': 'V1', 'bao': 'V1', 'bei': 'V1', 'ben': 'V1', 'beng': 'V1', 'bi': 'V1', 'bian': 'V1', 'biao': 'V1', 'bie': 'V1', 'bin': 'V1', 'bing': 'V1', 'bo': 'V1', 'bu': 'V1',
  'p': 'V1', 'pa': 'V1', 'pai': 'V1', 'pan': 'V1', 'pang': 'V1', 'pao': 'V1', 'pei': 'V1', 'pen': 'V1', 'peng': 'V1', 'pi': 'V1', 'pian': 'V1', 'piao': 'V1', 'pie': 'V1', 'pin': 'V1', 'ping': 'V1', 'po': 'V1', 'pu': 'V1',
  'm': 'V1', 'ma': 'V1', 'mai': 'V1', 'man': 'V1', 'mang': 'V1', 'mao': 'V1', 'mei': 'V1', 'men': 'V1', 'meng': 'V1', 'mi': 'V1', 'mian': 'V1', 'miao': 'V1', 'mie': 'V1', 'min': 'V1', 'ming': 'V1', 'mo': 'V1', 'mou': 'V1', 'mu': 'V1',
  
  // V2 - 唇齿音 (f, v)
  'f': 'V2', 'fa': 'V2', 'fan': 'V2', 'fang': 'V2', 'fei': 'V2', 'fen': 'V2', 'feng': 'V2', 'fo': 'V2', 'fou': 'V2', 'fu': 'V2',
  'v': 'V2', 'va': 'V2', 'van': 'V2', 'vang': 'V2', 'vei': 'V2', 'ven': 'V2', 'veng': 'V2', 'vo': 'V2', 'vou': 'V2', 'vu': 'V2',
  
  // V3 - 开口元音 (a, o, e, ai, ei, ao, ou, an, en, ang, eng, 以及大部分声母)
  'a': 'V3', 'ai': 'V3', 'an': 'V3', 'ang': 'V3', 'ao': 'V3',
  'o': 'V3', 'ou': 'V3',
  'e': 'V3', 'ei': 'V3', 'en': 'V3', 'eng': 'V3', 'er': 'V3',
  
  // 声母 + 开口元音组合
  'd': 'V3', 'da': 'V3', 'dai': 'V3', 'dan': 'V3', 'dang': 'V3', 'dao': 'V3', 'de': 'V3', 'dei': 'V3', 'den': 'V3', 'deng': 'V3', 'di': 'V3', 'dian': 'V3', 'diao': 'V3', 'die': 'V3', 'ding': 'V3', 'diu': 'V3', 'dong': 'V3', 'dou': 'V3', 'du': 'V3', 'duan': 'V3', 'dui': 'V3', 'dun': 'V3', 'duo': 'V3',
  't': 'V3', 'ta': 'V3', 'tai': 'V3', 'tan': 'V3', 'tang': 'V3', 'tao': 'V3', 'te': 'V3', 'tei': 'V3', 'ten': 'V3', 'teng': 'V3', 'ti': 'V3', 'tian': 'V3', 'tiao': 'V3', 'tie': 'V3', 'ting': 'V3', 'tong': 'V3', 'tou': 'V3', 'tu': 'V3', 'tuan': 'V3', 'tui': 'V3', 'tun': 'V3', 'tuo': 'V3',
  'n': 'V3', 'na': 'V3', 'nai': 'V3', 'nan': 'V3', 'nang': 'V3', 'nao': 'V3', 'ne': 'V3', 'nei': 'V3', 'nen': 'V3', 'neng': 'V3', 'ni': 'V3', 'nian': 'V3', 'niao': 'V3', 'nie': 'V3', 'nin': 'V3', 'ning': 'V3', 'niu': 'V3', 'nong': 'V3', 'nou': 'V3', 'nu': 'V3', 'nuan': 'V3', 'nue': 'V3', 'nun': 'V3', 'nuo': 'V3',
  'l': 'V3', 'la': 'V3', 'lai': 'V3', 'lan': 'V3', 'lang': 'V3', 'lao': 'V3', 'le': 'V3', 'lei': 'V3', 'leng': 'V3', 'li': 'V3', 'lia': 'V3', 'lian': 'V3', 'liang': 'V3', 'liao': 'V3', 'lie': 'V3', 'lin': 'V3', 'ling': 'V3', 'liu': 'V3', 'long': 'V3', 'lou': 'V3', 'lu': 'V3', 'luan': 'V3', 'lue': 'V3', 'lun': 'V3', 'luo': 'V3',
  'g': 'V3', 'ga': 'V3', 'gai': 'V3', 'gan': 'V3', 'gang': 'V3', 'gao': 'V3', 'ge': 'V3', 'gei': 'V3', 'gen': 'V3', 'geng': 'V3', 'gong': 'V3', 'gou': 'V3', 'gu': 'V3', 'gua': 'V3', 'guai': 'V3', 'guan': 'V3', 'guang': 'V3', 'gui': 'V3', 'gun': 'V3', 'guo': 'V3',
  'k': 'V3', 'ka': 'V3', 'kai': 'V3', 'kan': 'V3', 'kang': 'V3', 'kao': 'V3', 'ke': 'V3', 'ken': 'V3', 'keng': 'V3', 'kong': 'V3', 'kou': 'V3', 'ku': 'V3', 'kua': 'V3', 'kuai': 'V3', 'kuan': 'V3', 'kuang': 'V3', 'kui': 'V3', 'kun': 'V3', 'kuo': 'V3',
  'h': 'V3', 'ha': 'V3', 'hai': 'V3', 'han': 'V3', 'hang': 'V3', 'hao': 'V3', 'he': 'V3', 'hei': 'V3', 'hen': 'V3', 'heng': 'V3', 'hong': 'V3', 'hou': 'V3', 'hu': 'V3', 'hua': 'V3', 'huai': 'V3', 'huan': 'V3', 'huang': 'V3', 'hui': 'V3', 'hun': 'V3', 'huo': 'V3',
  'z': 'V3', 'za': 'V3', 'zai': 'V3', 'zan': 'V3', 'zang': 'V3', 'zao': 'V3', 'ze': 'V3', 'zei': 'V3', 'zen': 'V3', 'zeng': 'V3', 'zi': 'V3', 'zong': 'V3', 'zou': 'V3', 'zu': 'V3', 'zuan': 'V3', 'zui': 'V3', 'zun': 'V3', 'zuo': 'V3',
  'c': 'V3', 'ca': 'V3', 'cai': 'V3', 'can': 'V3', 'cang': 'V3', 'cao': 'V3', 'ce': 'V3', 'cen': 'V3', 'ceng': 'V3', 'ci': 'V3', 'cong': 'V3', 'cou': 'V3', 'cu': 'V3', 'cuan': 'V3', 'cui': 'V3', 'cun': 'V3', 'cuo': 'V3',
  's': 'V3', 'sa': 'V3', 'sai': 'V3', 'san': 'V3', 'sang': 'V3', 'sao': 'V3', 'se': 'V3', 'sen': 'V3', 'seng': 'V3', 'si': 'V3', 'song': 'V3', 'sou': 'V3', 'su': 'V3', 'suan': 'V3', 'sui': 'V3', 'sun': 'V3', 'suo': 'V3',
  'zh': 'V3', 'zha': 'V3', 'zhai': 'V3', 'zhan': 'V3', 'zhang': 'V3', 'zhao': 'V3', 'zhe': 'V3', 'zhei': 'V3', 'zhen': 'V3', 'zheng': 'V3', 'zhi': 'V3', 'zhong': 'V3', 'zhou': 'V3', 'zhu': 'V3', 'zhua': 'V3', 'zhuai': 'V3', 'zhuan': 'V3', 'zhuang': 'V3', 'zhui': 'V3', 'zhun': 'V3', 'zhuo': 'V3',
  'ch': 'V3', 'cha': 'V3', 'chai': 'V3', 'chan': 'V3', 'chang': 'V3', 'chao': 'V3', 'che': 'V3', 'chen': 'V3', 'cheng': 'V3', 'chi': 'V3', 'chong': 'V3', 'chou': 'V3', 'chu': 'V3', 'chua': 'V3', 'chuai': 'V3', 'chuan': 'V3', 'chuang': 'V3', 'chui': 'V3', 'chun': 'V3', 'chuo': 'V3',
  'sh': 'V3', 'sha': 'V3', 'shai': 'V3', 'shan': 'V3', 'shang': 'V3', 'shao': 'V3', 'she': 'V3', 'shei': 'V3', 'shen': 'V3', 'sheng': 'V3', 'shi': 'V3', 'shou': 'V3', 'shu': 'V3', 'shua': 'V3', 'shuai': 'V3', 'shuan': 'V3', 'shuang': 'V3', 'shui': 'V3', 'shun': 'V3', 'shuo': 'V3',
  'r': 'V3', 'ra': 'V3', 'ran': 'V3', 'rang': 'V3', 'rao': 'V3', 're': 'V3', 'ren': 'V3', 'reng': 'V3', 'ri': 'V3', 'rong': 'V3', 'rou': 'V3', 'ru': 'V3', 'rua': 'V3', 'ruan': 'V3', 'rui': 'V3', 'run': 'V3', 'ruo': 'V3',
  
  // V4 - 闭口音 (i, ü, u, in, ing, ün, üe)
  'i': 'V4', 'ia': 'V4', 'ian': 'V4', 'iang': 'V4', 'iao': 'V4', 'ie': 'V4', 'in': 'V4', 'ing': 'V4', 'iong': 'V4', 'iu': 'V4',
  'ü': 'V4', 'üa': 'V4', 'üan': 'V4', 'üang': 'V4', 'üe': 'V4', 'ün': 'V4', 'üo': 'V4',
  'u': 'V4', 'ua': 'V4', 'uai': 'V4', 'uan': 'V4', 'uang': 'V4', 'ue': 'V4', 'ui': 'V4', 'un': 'V4', 'uo': 'V4',
  
  // 声母 + 闭口音组合
  'j': 'V4', 'ji': 'V4', 'jia': 'V4', 'jian': 'V4', 'jiang': 'V4', 'jiao': 'V4', 'jie': 'V4', 'jin': 'V4', 'jing': 'V4', 'jiong': 'V4', 'jiu': 'V4', 'ju': 'V4', 'juan': 'V4', 'jue': 'V4', 'jun': 'V4',
  'q': 'V4', 'qi': 'V4', 'qia': 'V4', 'qian': 'V4', 'qiang': 'V4', 'qiao': 'V4', 'qie': 'V4', 'qin': 'V4', 'qing': 'V4', 'qiong': 'V4', 'qiu': 'V4', 'qu': 'V4', 'quan': 'V4', 'que': 'V4', 'qun': 'V4',
  'x': 'V4', 'xi': 'V4', 'xia': 'V4', 'xian': 'V4', 'xiang': 'V4', 'xiao': 'V4', 'xie': 'V4', 'xin': 'V4', 'xing': 'V4', 'xiong': 'V4', 'xiu': 'V4', 'xu': 'V4', 'xuan': 'V4', 'xue': 'V4', 'xun': 'V4',
  'y': 'V4', 'ya': 'V4', 'yan': 'V4', 'yang': 'V4', 'yao': 'V4', 'ye': 'V4', 'yi': 'V4', 'yin': 'V4', 'ying': 'V4', 'yong': 'V4', 'you': 'V4', 'yu': 'V4', 'yuan': 'V4', 'yue': 'V4', 'yun': 'V4',
  'w': 'V4', 'wa': 'V4', 'wai': 'V4', 'wan': 'V4', 'wang': 'V4', 'wei': 'V4', 'wen': 'V4', 'weng': 'V4', 'wo': 'V4', 'wu': 'V4'
};

// Viseme到BlendShape参数的映射配置
const VISEME_TO_BLENDSHAPE_MAP: Record<string, any> = {
  'V0': {
    viseme: 'V0',
    description: '静音（自然闭合）',
    blendShapeParams: {
      mouthOpen: 0.0, mouthClose: 1.0, mouthPucker: 0.0, mouthFrown: 0.0, 
      mouthSmile: 0.0, mouthWide: 0.0, jawOpen: 0.0, tongueOut: 0.0, cheekPuff: 0.0
    },
    transitionTime: 20
  },
  'V1': {
    viseme: 'V1',
    description: '双唇音 (b, p, m)',
    blendShapeParams: {
      mouthOpen: 0.0, mouthClose: 1.0, mouthPucker: 1.0, mouthFrown: 0.0, 
      mouthSmile: 0.0, mouthWide: 0.0, jawOpen: 0.0, tongueOut: 0.0, cheekPuff: 0.0
    },
    transitionTime: 30
  },
  'V2': {
    viseme: 'V2',
    description: '唇齿音 (f, v)',
    blendShapeParams: {
      mouthOpen: 0.2, mouthClose: 0.8, mouthPucker: 0.0, mouthFrown: 0.5, 
      mouthSmile: 0.0, mouthWide: 0.0, jawOpen: 0.1, tongueOut: 0.0, cheekPuff: 0.0
    },
    transitionTime: 25
  },
  'V3': {
    viseme: 'V3',
    description: '开口元音 (a, o, e)',
    blendShapeParams: {
      mouthOpen: 1.0, mouthClose: 0.0, mouthPucker: 0.0, mouthFrown: 0.0, 
      mouthSmile: 0.0, mouthWide: 0.3, jawOpen: 0.8, tongueOut: 0.0, cheekPuff: 0.0
    },
    transitionTime: 50
  },
  'V4': {
    viseme: 'V4',
    description: '闭口音 (i, ü, u)',
    blendShapeParams: {
      mouthOpen: 0.2, mouthClose: 0.8, mouthPucker: 0.0, mouthFrown: 0.0, 
      mouthSmile: 0.3, mouthWide: 0.0, jawOpen: 0.1, tongueOut: 0.0, cheekPuff: 0.0
    },
    transitionTime: 40
  }
};

// 时间戳到Viseme序列转换器
class TimestampToVisemeConverter {
  // 将时间戳数据转换为Viseme时间序列
  convertTimestampsToVisemes(timestamps: TimestampData[]): VisemeTimeline[] {
    const visemeTimeline: VisemeTimeline[] = [];
    
    for (const timestamp of timestamps) {
      const viseme = this.getVisemeFromText(timestamp.text);
      const duration = timestamp.end - timestamp.start;
      
      visemeTimeline.push({
        viseme,
        startTime: timestamp.start,
        endTime: timestamp.end,
        duration,
        text: timestamp.text,
        phoneme: timestamp.phoneme
      });
    }
    
    return visemeTimeline;
  }
  
  // 从文本获取Viseme
  private getVisemeFromText(text: string): string {
    // 处理标点符号和空格
    if (PINYIN_TO_VISEME_MAP[text]) {
      return PINYIN_TO_VISEME_MAP[text];
    }
    
    // 处理拼音（移除声调）
    const cleanText = text.replace(/[1-4]/g, '').toLowerCase();
    if (PINYIN_TO_VISEME_MAP[cleanText]) {
      return PINYIN_TO_VISEME_MAP[cleanText];
    }
    
    // 模糊匹配
    for (const [key, viseme] of Object.entries(PINYIN_TO_VISEME_MAP)) {
      if (cleanText.includes(key) || key.includes(cleanText)) {
        return viseme;
      }
    }
    
    // 默认返回V3
    return 'V3';
  }
}

// Viseme时序管理器
class VisemeTimelineManager {
  private timeline: VisemeTimeline[] = [];
  private currentIndex: number = 0;
  private startTime: number = 0;
  private isPlaying: boolean = false;
  
  // 设置Viseme时间序列
  setTimeline(timeline: VisemeTimeline[]): void {
    this.timeline = timeline;
    this.currentIndex = 0;
  }
  
  // 开始播放
  start(): void {
    this.isPlaying = true;
    this.startTime = Date.now();
    this.currentIndex = 0;
  }
  
  // 停止播放
  stop(): void {
    this.isPlaying = false;
    this.currentIndex = 0;
  }
  
  // 更新当前Viseme
  update(): string | null {
    if (!this.isPlaying || this.timeline.length === 0) {
      return null;
    }
    
    const currentTime = Date.now() - this.startTime;
    
    // 查找当前时间对应的Viseme
    for (let i = this.currentIndex; i < this.timeline.length; i++) {
      const item = this.timeline[i];
      
      if (currentTime >= item.startTime && currentTime <= item.endTime) {
        this.currentIndex = i;
        return item.viseme;
      }
      
      // 如果当前时间已经超过这个Viseme，继续查找下一个
      if (currentTime > item.endTime) {
        continue;
      }
    }
    
    // 如果所有Viseme都播放完了
    if (currentTime > this.timeline[this.timeline.length - 1].endTime) {
      this.isPlaying = false;
      return 'V0'; // 返回静音状态
    }
    
    return null;
  }
  
  // 获取当前Viseme信息
  getCurrentVisemeInfo(): VisemeTimeline | null {
    if (this.currentIndex < this.timeline.length) {
      return this.timeline[this.currentIndex];
    }
    return null;
  }
  
  // 获取播放进度
  getProgress(): number {
    if (this.timeline.length === 0) return 0;
    
    const currentTime = Date.now() - this.startTime;
    const totalDuration = this.timeline[this.timeline.length - 1].endTime;
    
    return Math.min(currentTime / totalDuration, 1.0);
  }
}

// 高级插值管理器
class AdvancedInterpolationManager {
  private currentParams: any = {};
  private targetParams: any = {};
  private startParams: any = {};
  private startTime: number = 0;
  private config: InterpolationConfig;
  private isInterpolatingActive: boolean = false;
  
  constructor() {
    this.config = {
      type: InterpolationType.EASE_IN_OUT,
      duration: 50
    };
  }
  
  // 开始插值
  startInterpolation(
    currentParams: any, 
    targetParams: any, 
    config?: Partial<InterpolationConfig>
  ): void {
    this.currentParams = { ...currentParams };
    this.startParams = { ...currentParams };
    this.targetParams = { ...targetParams };
    
    this.config = { ...this.config, ...config };
    this.startTime = Date.now();
    this.isInterpolatingActive = true;
  }
  
  // 更新插值
  updateInterpolation(): any | null {
    if (!this.isInterpolatingActive) {
      return null;
    }
    
    const elapsed = Date.now() - this.startTime;
    const progress = Math.min(elapsed / this.config.duration, 1.0);
    
    // 应用缓动函数
    const easedProgress = this.applyEasing(progress);
    
    // 插值计算
    const interpolatedParams = this.interpolateParams(easedProgress);
    
    // 更新当前参数
    this.currentParams = interpolatedParams;
    
    // 检查是否完成
    if (progress >= 1.0) {
      this.isInterpolatingActive = false;
      this.currentParams = { ...this.targetParams };
    }
    
    return this.currentParams;
  }
  
  // 应用缓动函数
  private applyEasing(progress: number): number {
    switch (this.config.type) {
      case InterpolationType.LINEAR:
        return progress;
        
      case InterpolationType.EASE_IN_OUT:
        return progress < 0.5 
          ? 2 * progress * progress 
          : 1 - Math.pow(-2 * progress + 2, 2) / 2;
          
      case InterpolationType.EASE_IN:
        return progress * progress;
        
      case InterpolationType.EASE_OUT:
        return 1 - Math.pow(1 - progress, 2);
        
      default:
        return progress;
    }
  }
  
  // 参数插值
  private interpolateParams(progress: number): any {
    const result: any = {};
    
    // 获取所有参数键
    const allKeys = new Set([
      ...Object.keys(this.startParams),
      ...Object.keys(this.targetParams)
    ]);
    
    allKeys.forEach(key => {
      const startValue = this.startParams[key] || 0;
      const targetValue = this.targetParams[key] || 0;
      
      // 线性插值
      result[key] = startValue + (targetValue - startValue) * progress;
    });
    
    return result;
  }
  
  // 检查是否正在插值
  isInterpolating(): boolean {
    return this.isInterpolatingActive;
  }
  
  // 获取当前参数
  getCurrentParams(): any {
    return this.currentParams;
  }
}

// 智能过渡管理器
class SmartTransitionManager {
  private interpolationManager: AdvancedInterpolationManager;
  private visemeHistory: string[] = [];
  private transitionRules: Map<string, InterpolationConfig> = new Map();
  
  constructor() {
    this.interpolationManager = new AdvancedInterpolationManager();
    this.setupTransitionRules();
  }
  
  // 设置过渡规则
  private setupTransitionRules(): void {
    // 定义不同Viseme之间的过渡规则
    this.transitionRules.set('V0->V1', { type: InterpolationType.EASE_IN_OUT, duration: 30 });
    this.transitionRules.set('V0->V2', { type: InterpolationType.EASE_IN_OUT, duration: 25 });
    this.transitionRules.set('V0->V3', { type: InterpolationType.EASE_IN_OUT, duration: 50 });
    this.transitionRules.set('V0->V4', { type: InterpolationType.EASE_IN_OUT, duration: 40 });
    
    this.transitionRules.set('V1->V0', { type: InterpolationType.EASE_OUT, duration: 20 });
    this.transitionRules.set('V1->V2', { type: InterpolationType.LINEAR, duration: 35 });
    this.transitionRules.set('V1->V3', { type: InterpolationType.EASE_IN_OUT, duration: 60 });
    this.transitionRules.set('V1->V4', { type: InterpolationType.EASE_IN_OUT, duration: 45 });
    
    this.transitionRules.set('V2->V0', { type: InterpolationType.EASE_OUT, duration: 25 });
    this.transitionRules.set('V2->V1', { type: InterpolationType.LINEAR, duration: 35 });
    this.transitionRules.set('V2->V3', { type: InterpolationType.EASE_IN_OUT, duration: 55 });
    this.transitionRules.set('V2->V4', { type: InterpolationType.EASE_IN_OUT, duration: 40 });
    
    this.transitionRules.set('V3->V0', { type: InterpolationType.EASE_OUT, duration: 30 });
    this.transitionRules.set('V3->V1', { type: InterpolationType.EASE_IN_OUT, duration: 60 });
    this.transitionRules.set('V3->V2', { type: InterpolationType.EASE_IN_OUT, duration: 55 });
    this.transitionRules.set('V3->V4', { type: InterpolationType.EASE_IN_OUT, duration: 50 });
    
    this.transitionRules.set('V4->V0', { type: InterpolationType.EASE_OUT, duration: 25 });
    this.transitionRules.set('V4->V1', { type: InterpolationType.EASE_IN_OUT, duration: 45 });
    this.transitionRules.set('V4->V2', { type: InterpolationType.EASE_IN_OUT, duration: 40 });
    this.transitionRules.set('V4->V3', { type: InterpolationType.EASE_IN_OUT, duration: 50 });
  }
  
  // 开始过渡
  startTransition(currentViseme: string, targetViseme: string): void {
    // 记录历史
    this.visemeHistory.push(currentViseme);
    if (this.visemeHistory.length > 5) {
      this.visemeHistory.shift();
    }
    
    // 获取过渡配置
    const transitionKey = `${currentViseme}->${targetViseme}`;
    const config = this.transitionRules.get(transitionKey) || {
      type: InterpolationType.EASE_IN_OUT,
      duration: 50
    };
    
    // 获取当前和目标参数
    const currentParams = this.getVisemeParams(currentViseme);
    const targetParams = this.getVisemeParams(targetViseme);
    
    // 开始插值
    this.interpolationManager.startInterpolation(currentParams, targetParams, config);
  }
  
  // 更新过渡
  updateTransition(): any | null {
    return this.interpolationManager.updateInterpolation();
  }
  
  // 检查是否正在过渡
  isTransitioning(): boolean {
    return this.interpolationManager.isInterpolating();
  }
  
  // 获取Viseme参数
  private getVisemeParams(viseme: string): any {
    const config = VISEME_TO_BLENDSHAPE_MAP[viseme];
    return config ? config.blendShapeParams : VISEME_TO_BLENDSHAPE_MAP['V0'].blendShapeParams;
  }
}

// 完整的平滑口型同步系统
class SmoothLipsyncSystem {
  private timelineManager: VisemeTimelineManager;
  private transitionManager: SmartTransitionManager;
  private morphTargets: any[];
  private faceMeshes: any[];
  private jawBone: any;
  private animationId: number | null = null;
  private currentViseme: string = 'V0';
  private targetViseme: string = 'V0';
  private isPlaying: boolean = false;
  
  constructor(morphTargets: any[], faceMeshes: any[], jawBone: any) {
    this.morphTargets = morphTargets;
    this.faceMeshes = faceMeshes;
    this.jawBone = jawBone;
    
    this.timelineManager = new VisemeTimelineManager();
    this.transitionManager = new SmartTransitionManager();
  }
  
  // 开始口型同步
  startLipsync(timestamps: TimestampData[]): void {
    // 转换时间戳为Viseme序列
    const converter = new TimestampToVisemeConverter();
    const visemeTimeline = converter.convertTimestampsToVisemes(timestamps);
    
    console.log('🎭 生成的Viseme时间序列:', visemeTimeline);
    
    // 设置时间序列
    this.timelineManager.setTimeline(visemeTimeline);
    
    // 开始播放
    this.timelineManager.start();
    this.isPlaying = true;
    
    // 开始动画循环
    this.startAnimationLoop();
  }
  
  // 停止口型同步
  stopLipsync(): void {
    this.isPlaying = false;
    this.timelineManager.stop();
    this.transitionManager.startTransition(this.currentViseme, 'V0');
    
    if (this.animationId) {
      cancelAnimationFrame(this.animationId);
      this.animationId = null;
    }
  }
  
  // 开始动画循环
  private startAnimationLoop(): void {
    const animate = () => {
      if (!this.isPlaying) {
        return;
      }
      
      // 更新当前Viseme
      const newViseme = this.timelineManager.update();
      
      if (newViseme && newViseme !== this.targetViseme) {
        // 开始过渡到新的Viseme
        this.transitionManager.startTransition(this.currentViseme, newViseme);
        this.targetViseme = newViseme;
        console.log(`🎭 Viseme变化: ${this.currentViseme} -> ${newViseme}`);
      }
      
      // 更新过渡
      const interpolatedParams = this.transitionManager.updateTransition();
      
      if (interpolatedParams) {
        // 应用到3D模型
        this.applyParamsToModel(interpolatedParams);
      }
      
      // 继续动画循环
      this.animationId = requestAnimationFrame(animate);
    };
    
    animate();
  }
  
  // 应用参数到3D模型
  private applyParamsToModel(params: any): void {
    // 应用嘴部形态参数
    this.applyMouthMorphs(params);
    
    // 应用下颌参数
    this.applyJawMorphs(params);
    
    // 应用面部网格参数
    this.applyFaceMorphs(params);
  }
  
  // 应用嘴部形态参数
  private applyMouthMorphs(params: any): void {
    this.morphTargets.forEach(morphTarget => {
      const name = morphTarget.name.toLowerCase();
      
      // 嘴张开度
      if (name.includes('mouth') && name.includes('open')) {
        morphTarget.influence = this.clamp(params.mouthOpen, 0, 1);
      }
      // 嘴闭合度
      else if (name.includes('mouth') && name.includes('close')) {
        morphTarget.influence = this.clamp(params.mouthClose, 0, 1);
      }
      // 嘴撅起度
      else if (name.includes('mouth') && name.includes('pucker')) {
        morphTarget.influence = this.clamp(params.mouthPucker, 0, 1);
      }
      // 嘴角下垂度
      else if (name.includes('mouth') && name.includes('frown')) {
        morphTarget.influence = this.clamp(params.mouthFrown, 0, 1);
      }
      // 嘴角上扬度
      else if (name.includes('mouth') && name.includes('smile')) {
        morphTarget.influence = this.clamp(params.mouthSmile, 0, 1);
      }
      // 嘴宽度
      else if (name.includes('mouth') && name.includes('wide')) {
        morphTarget.influence = this.clamp(params.mouthWide, 0, 1);
      }
      // 舌头伸出度
      else if (name.includes('tongue') && name.includes('out')) {
        morphTarget.influence = this.clamp(params.tongueOut, 0, 1);
      }
      // 脸颊鼓起度
      else if (name.includes('cheek') && name.includes('puff')) {
        morphTarget.influence = this.clamp(params.cheekPuff, 0, 1);
      }
    });
  }
  
  // 应用下颌参数
  private applyJawMorphs(params: any): void {
    if (this.jawBone && this.jawBone.rotation) {
      const jawRotation = this.clamp(params.jawOpen, 0, 1) * 0.3;
      this.jawBone.rotation.x = jawRotation;
    }
  }
  
  // 应用面部网格参数
  private applyFaceMorphs(_params: any): void {
    this.faceMeshes.forEach(mesh => {
      if (mesh.morphTargetInfluences) {
        // 根据参数调整面部网格
        // 这里可以根据需要添加更多面部表情控制
      }
    });
  }
  
  // 数值限制
  private clamp(value: number, min: number, max: number): number {
    return Math.min(Math.max(value, min), max);
  }
  
  // 获取当前状态
  getCurrentState(): { viseme: string; isPlaying: boolean; progress: number } {
    return {
      viseme: this.currentViseme,
      isPlaying: this.isPlaying,
      progress: this.timelineManager.getProgress()
    };
  }
}

// React Hook for Advanced Lipsync
export const useAdvancedLipsync = (
  morphTargets: any[], 
  faceMeshes: any[], 
  jawBone: any
) => {
  const lipsyncRef = useRef<SmoothLipsyncSystem | null>(null);
  
  // 初始化口型同步系统
  const initializeLipsync = useCallback(() => {
    if (!lipsyncRef.current) {
      lipsyncRef.current = new SmoothLipsyncSystem(morphTargets, faceMeshes, jawBone);
      console.log('🎭 高级口型同步系统已初始化');
    }
  }, [morphTargets, faceMeshes, jawBone]);
  
  // 开始口型同步
  const startLipsync = useCallback((timestamps: TimestampData[]) => {
    if (lipsyncRef.current) {
      lipsyncRef.current.startLipsync(timestamps);
    }
  }, []);
  
  // 停止口型同步
  const stopLipsync = useCallback(() => {
    if (lipsyncRef.current) {
      lipsyncRef.current.stopLipsync();
    }
  }, []);
  
  // 获取当前状态
  const getCurrentState = useCallback(() => {
    if (lipsyncRef.current) {
      return lipsyncRef.current.getCurrentState();
    }
    return { viseme: 'V0', isPlaying: false, progress: 0 };
  }, []);
  
  return {
    initializeLipsync,
    startLipsync,
    stopLipsync,
    getCurrentState
  };
};

export default useAdvancedLipsync;